package com.tedu.mall.controller;
import com.tedu.mall.mapper.UserMapper;
import com.tedu.mall.pojo.User;
import com.tedu.mall.pojo.UserExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@CrossOrigin
public class userController {
    @Autowired
    UserMapper userMapper;
    //登录
    @RequestMapping("/user/login")
    @CrossOrigin
    public User login(User user){
        UserExample userExample=new UserExample();
        UserExample.Criteria criteria = userExample.or();
        criteria.andUsernameEqualTo(user.getUsername());
        criteria.andPasswordEqualTo(user.getPassword());
        List<User> list=userMapper.selectByExample(userExample);
        //判断集合
        if(list!=null&&list.size()>=1){
            User dbUser=list.get(0);
            //设置密码为空
            dbUser.setPassword("");
            return dbUser;
        }
        return  null;
        //登录失败应该返回状态码
    }
    //注册
    @RequestMapping("/user/register")
    @CrossOrigin//允许别的网站用js访问该网站
    public String register(User user) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.or();
        criteria.andUsernameEqualTo(user.getUsername());
        List<User> list=userMapper.selectByExample(userExample);
        if(list!=null&&list.size()==0){
        int count=userMapper.insert(user);
        if(count>=1){
            return "注册成功";
        }
        else{
            return "注册失败";
        }
        }else{
            return "用户名已经存在";
        }

    }
   @RequestMapping("/test")
   public List<User> test(){
       return userMapper.selectByExample(null);
   }
}
